angular.module('starter.services', [])

.constant('ApiEndpoint', {
	url : "../../"
})

.factory('settings', ['$rootScope', 'Page', function($rootScope, Page) {
	var settings = {};
	
	var __local = window.location;
	var __contextPath = __local.pathname.split("/")[1];
	var __basePath = __local.protocol+"//"+__local.host+"/"+__contextPath;
	settings.basePath = __basePath;
	$rootScope.settings = settings;
    $rootScope.screenWidth = document.body.clientWidth;
    $rootScope.screenHeight = window.innerHeight;
    return settings;
}])

.factory('localStore',['$window',function($window){
	return{        //存储单个属性
		set :function(key,value){
		  $window.localStorage[key]=value;
		},        //读取单个属性
		get:function(key,defaultValue){
		  return  $window.localStorage[key] || defaultValue;
		},        //存储对象，以JSON格式存储
		setObject:function(key,value){
		  $window.localStorage[key]=JSON.stringify(value);
		},        //读取对象
		getObject: function (key) {
		  return JSON.parse($window.localStorage[key] || '{}');
		}
     }
 }])
 .factory('sessionStore',['$window',function($window){
	return{        //存储单个属性
		set :function(key,value){
		  $window.sessionStorage[key]=value;
		},        //读取单个属性
		get:function(key,defaultValue){
		  return  $window.sessionStorage[key] || defaultValue;
		},        //存储对象，以JSON格式存储
		setObject:function(key,value){
		  $window.sessionStorage[key]=JSON.stringify(value);
		},        //读取对象
		getObject: function (key) {
		  return JSON.parse($window.sessionStorage[key] || '{}');
		}
     }
 }])

.factory('HttpInterceptor', function () {
    // ---
    // PRVIATE METHODS.
    // ---
    // I serialize the given Object into a key-value pair string. This
    // method expects an object and will default to the toString() method.
    // --
    // NOTE: This is an atered version of the jQuery.param() method which
    // will serialize a data collection for Form posting.
    // --
    // https://github.com/jquery/jquery/blob/master/src/serialize.js#L45
    function serializeData(data) {
        // If this is not an object, defer to native stringification.
        if (!angular.isObject(data)) {
            return ((data == null) ? "" : data.toString());
        }
        var buffer = [];
        // Serialize each key in the object.
        for (var name in data) {
            if (!data.hasOwnProperty(name)) {
                continue;
            }
            var value = data[name];
            if (angular.isObject(value)) {
                value = angular.toJson(value);
            }
            buffer.push(encodeURIComponent(name) + "=" + encodeURIComponent((value == null) ? "" : value));
        }
        // Serialize the buffer and clean it up for transportation.
        var source = buffer.join("&").replace(/%20/g, "+");
        return (source);
    }

    return {
        request: function (config) {
            if (config.data && angular.isObject(config.data)) {
                if (config.method === 'POST') {
                    config.data = serializeData(config.data);
                } else if (config.method === 'GET') {
                    config.url += (config.url.indexOf('?') > 0 ? '&' : '?') + serializeData(config.data);
                }
            }

            return config;
        }
    };
})

.service('Page', function($rootScope, $http, $state, ApiEndpoint,$ionicPopup) { // injectables go here
	var self = this; // Save reference

	this.alert = function(message, yesCallback) {
		layer.open({
			content : message,
			btn : ['OK'],
			yes : function(index) {
				if (yesCallback) {
					layer.close(index)
					yesCallback();
				}
			}
		});
	};

	this.notice = function(message) {
		layer.open({
			content : message,
			time : 2
		});
	};

	this.confirm = function(message, yesCallback) {
		layer.open({
			content : message,
			btn : ['确认', '取消'],
			shadeClose : false,
			anim : false,
			yes : function(index) {
				if (yesCallback) {
					layer.close(index)
					yesCallback();
				}
			},
			no : function() {
			}
		});
	};

	this.ajax = function(method, url, data, isFilter, callback, errorCallback) {
		var loadi = null;
		//取消layer弹框，改为ionic弹框
		/*if (isFilter) {
			loadi = layer.open({
				type : 2,
				content : ''
			});
		}*/
		
		var alertPopup = $ionicPopup.alert({
            cssClass : 'popup_radius popup_notitle popup_cleanwidth popup_black',
            template: '<ion-spinner icon="ios-small"></ion-spinner>',
            buttons:null
        });
		data = data || {};
		$http({
			method : method,
			url : ApiEndpoint.url + url,
			data : data,
			cache : false
		}).success(function(response) {
			/*if (loadi != null) {
				layer.close(loadi);
			}*/
			alertPopup.close(); // 关闭弹窗
			if (response.resultCode == '1' || url.indexOf('service/') == 0) { //成功
				if (callback) {
					callback(response);
				}
			} else if (errorCallback) {
				errorCallback(response)
			} else if (response.resultCode) {
				self.notice(response.resultDes);
			}
		});
	};

	this.ajaxPost = function(url, data, callback, errorCallback) {
		this.ajax('POST', url, data, true, callback, errorCallback);
	};

	this.ajaxPostQuiet = function(url, data, callback, errorCallback) {
		this.ajax('POST', url, data, false, callback, errorCallback);
	};

	this.ajaxGet = function(url, data, callback, errorCallback) {
		this.ajax('GET', url, data, true, callback, errorCallback);
	};

	this.ajaxGetQuiet = function(url, data, callback, errorCallback) {
		this.ajax('GET', url, data, false, callback, errorCallback);
	};

	this.ajaxPut = function(url, data, callback, errorCallback) {
		if (!data) {
			data = {};
		}
		data._method = 'PUT';
		this.ajaxPost(url, data, callback, errorCallback);
	},

	this.ajaxDelete = function(url, data, callback, errorCallback) {
		if (!data) {
			data = {};
		}
		data._method = 'DELETE';
		this.ajaxPost(url, data, callback, errorCallback);
	}

})

var AppUtil = function () {
	return {

		// 获取model的小数点最后部分
		getModelName: function(modelName) {
			if (modelName.indexOf('.') > 0) {
				modelName = modelName.substring(modelName.lastIndexOf('.') + 1, modelName.length);
			}
			return modelName;
		},
	
		// 获取model的小数点最后部分
		getModelValue: function(scope, modelName) {
			if (modelName.indexOf('.') > 0) {
				var arr = modelName.split('.');
				var value = scope;
				$(arr).each(function(ii, modelName2) {
					if (angular.isUndefined(value)) {
						value = null;
						return false;
					} else {
						value = value[modelName2];
					}
				});
				return value;
			} else {
				return scope[modelName];
			}
		},
	
		jsonfy: function(json) {
			//return jsonfy('{' + (json || '') + '}');
			return eval('[{' + (json || '') + '}]')[0];
		}
	}
}();
